import tkinter as tk
from PIL import Image, ImageTk
import os

from .placeholderentry import PlaceholderEntry
from utils import resource_path, log_info, log_exception, log_warning, log_debug
from services import UserService, HomeService
from models.user import User
from configs.config import COPY_RIGHT, FONT_CONFIG
from app_state import app_state
from .home_view import HomeView

class LoginView(tk.Frame):
    """登录视图类，负责登录界面的UI展示"""
    def __init__(self, root, parent, style=None):
        super().__init__(root)
        self.root = root
        self.style = style  # 使用传入的样式对象
        self.user_service = UserService()  # 初始化用户服务

        # 确保中文显示正常
        self.font = FONT_CONFIG['login']

        self.app = parent

        # 创建画布作为背景
        self.canvas = tk.Canvas(self, width=1024, height=768)
        self.canvas.pack(fill="both", expand=True)

        # 加载背景图片
        self.load_background_image()

        # 创建登录相关组件
        self.create_login_widgets()

    def load_background_image(self):
        try:
            # 检查图片是否存在
            image_path = resource_path(os.path.join("icon", "login_bg.png"))
            if not os.path.exists(image_path):
                log_warning(f"警告: 找不到背景图片 {image_path}")
                return

            # 加载并调整图片大小
            bg_image = Image.open(image_path)
            bg_image = bg_image.resize((1024, 768), Image.Resampling.LANCZOS)
            self.bg_photo = ImageTk.PhotoImage(bg_image)

            # 在画布上显示背景图片
            self.canvas.create_image(0, 0, image=self.bg_photo, anchor="nw")
        except Exception as e:
            log_exception(f"加载背景图片出错: {e}")
            # 如果加载失败，设置一个灰色背景
            self.canvas.configure(bg="#f0f0f0")

    def load_icons(self):
        """加载并返回图标图片"""
        icons = {}
        try:
            # 获取当前文件目录
            current_dir = os.path.dirname(__file__)

            # 加载用户名图标
            username_icon_path = resource_path(os.path.join("icon", "login_username.png"))
            if os.path.exists(username_icon_path):
                username_icon = Image.open(username_icon_path)
                username_icon = username_icon.resize((35, 35), Image.Resampling.LANCZOS)
                icons["username"] = ImageTk.PhotoImage(username_icon)
            else:
                log_warning(f"警告: 找不到用户名图标 {username_icon_path}")
                icons["username"] = None

            # 加载身份证图标
            idcard_icon_path = resource_path(os.path.join("icon", "login_idcard.png"))
            if os.path.exists(idcard_icon_path):
                idcard_icon = Image.open(idcard_icon_path)
                idcard_icon = idcard_icon.resize((40, 35), Image.Resampling.LANCZOS)
                icons["idcard"] = ImageTk.PhotoImage(idcard_icon)
            else:
                log_warning(f"警告: 找不到身份证图标 {idcard_icon_path}")
                icons["idcard"] = None

        except Exception as e:
            log_exception(f"加载图标出错: {e}")

        return icons

    def create_login_widgets(self):
        # 加载图标
        self.icons = self.load_icons()

        # 在用户名输入框前添加图标
        if self.icons["username"]:
            self.canvas.create_image(330, 302, image=self.icons["username"], anchor="nw")

        # 创建无边框样式
        self.style.configure("NoBorder.TEntry", 
                bordercolor="",  # 移除边框颜色
                lightcolor="",    # 移除亮边
                darkcolor="",     # 移除暗边
                borderwidth=0,    # 边框宽度设为0
                relief="flat",    # 无浮雕效果
                padding=0,        # 移除内边距
                highlightthickness=0,  # 移除高亮厚度
                focuscolor=""    # 移除焦点颜色
        )

        self.style.map("NoBorder.TEntry",
                bordercolor=[('focus', '')],   # 焦点状态下边框颜色为空
                lightcolor=[('focus', '')],     # 焦点状态下亮边为空
                darkcolor=[('focus', '')],      # 焦点状态下暗边为空
                borderwidth=[('focus', 0)],     # 焦点状态下边框宽度为0
                relief=[('focus', 'flat')],     # 焦点状态下无浮雕
                highlightthickness=[('focus', 0)] # 焦点状态下无高亮
        )

        # 创建用户名输入框（带 placeholder）
        self.username_entry = PlaceholderEntry(
            self.root,
            placeholder="请输入用户名",
            font=self.font,
            width=30,
            style="NoBorder.TEntry",
            is_password=False
        )
        self.username_entry.place(x=370, y=289, height=65, width=300)

        # 在密码输入框前添加图标
        if self.icons["idcard"]:
            self.canvas.create_image(330, 402, image=self.icons["idcard"], anchor="nw")

        # 创建密码输入框（带 placeholder）
        self.id_card_entry = PlaceholderEntry(
            self.root,
            placeholder="请输入身份证号",
            font=self.font,
            width=30,
            style="NoBorder.TEntry",
            is_password=False
        )
        self.id_card_entry.place(x=370, y=388, height=65, width=300)

        # 创建透明背景的点击区域
        self.transparent_area = self.canvas.create_text(
                550, 
                470, 
                text="", 
                font=self.font, 
                fill="black", 
                tags="login_area"
        )

        # 为文本区域添加矩形背景以增加点击区域
        self.canvas.create_rectangle(320, 500, 705, 565, outline="black", width=0, tags="login_area")

        # 绑定点击事件到画布上的登录区域
        self.canvas.tag_bind("login_area", "<Button-1>", self.get_input_content)

        # 绑定鼠标进入和离开事件以改变光标样式
        self.canvas.tag_bind("login_area", "<Enter>", self.on_mouse_enter)
        self.canvas.tag_bind("login_area", "<Leave>", self.on_mouse_leave)

        # 在右下角添加版权信息
        self.canvas.create_text(
            715,  # x坐标，距离右边44像素
            740,  # y坐标，距离底部28像素
            text=COPY_RIGHT,
            font=("SimHei", 12),
            fill="#666666",
            anchor="ne",  # 右上角对齐
            tags="copyright"
        )

    def on_mouse_enter(self, event):
        """鼠标进入登录区域时，将光标更改为小手形状"""
        self.canvas.config(cursor="hand2")

    def on_mouse_leave(self, event):
        """鼠标离开登录区域时，将光标恢复为默认形状"""
        self.canvas.config(cursor="arrow")

    def login(self, username, id_card):
        try:
            # 调用UserService进行登录验证
            result = self.user_service.login(username, id_card)
            
            if result['success']:
                # 登录成功
                user_info = result['user_info']
                user = User.from_dict(user_info)
                log_debug(f"用户 {username} 登录成功")
                
                if self.on_login_success:
                    self.on_login_success(user)
                return True
            else:
                # 登录失败
                error_message = result.get('message', '登录失败，请重试')
                self.show_error_message(error_message)
                log_debug(f"用户 {username} 登录失败: {error_message}")
                return False
        except Exception as e:
            error_message = f"登录失败: {str(e)}"
            self.show_error_message(error_message)
            log_exception(error_message)
            return False

    def get_input_content(self, event=None):
        # 获取输入框内容（使用get_real_value过滤placeholder）
        username = self.username_entry.get_real_value()
        id_card = self.id_card_entry.get_real_value()

        # 清除之前显示的内容
        self.canvas.delete("display_content")

        if username == "" or id_card == "":
            # 在登录按钮下方显示输入内容
            self.canvas.create_text(
                505, 
                590, 
                text=f"用户名或身份证号不能为空", 
                font=("SimHei", 16), 
                fill="red", 
                tags="display_content"
            )
            return

        # 调用login方法进行登录
        self.login(username, id_card)

    def show_error_message(self, message: str):
        """显示错误消息"""
        self.canvas.delete("display_content")
        self.canvas.create_text(
            505, 
            590, 
            text=message, 
            font=("SimHei", 16), 
            fill="red", 
            tags="display_content"
        )

    # 定义登录成功回调函数
    def on_login_success(self, user):
        # 更新应用状态
        app_state.set_user(user)
        # 登录成功后创建主框架
        self.create_main_frame()

    def create_main_frame(self):
        
        # 保存当前练习进度
        if hasattr(self, 'current_category') and hasattr(self, 'current_practice_index') and app_state.current_user_id:
            home_service = HomeService()
            home_service.save_practice_progress(app_state.current_category, app_state.current_practice_index, app_state.current_user_id)


        # 创建HomeView实例
        self.home_view = HomeView(
            self.root,
            application=self.app,
            style=self.style
        )